package com.daxia.ogmall.event;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.daxia.ogmall.dto.ProductDTO;
import com.daxia.ogmall.model.Specification;
import com.daxia.ogmall.service.ProductService;

@Component
public class SpecificationChangedListener implements ApplicationListener<SpecificationChangedEvent> {
	
	@Autowired
	private ProductService productService;
	
	@Override
	@Transactional
	public void onApplicationEvent(SpecificationChangedEvent event) {
		Long productId = (Long) event.getSource();
		ProductDTO p = productService.load(productId);
		List<Specification> specs = p.getSpecifications();
		if (CollectionUtils.isNotEmpty(specs)) {
			List<String> images = new ArrayList<String>();
			List<String> codes = new ArrayList<String>();
			for (Specification specification : specs) {
				if (StringUtils.isNotBlank(specification.getImages())) {
					String[] arr = specification.getImages().split(",");
					for (String string : arr) {
						images.add(string);
					}
				}
				if (StringUtils.isNotBlank(specification.getOgCode())) {
					codes.add(specification.getOgCode());
				}
				if (StringUtils.isNotBlank(specification.getFactoryCode())) {
					codes.add(specification.getFactoryCode());
				}
			}
			if (CollectionUtils.isNotEmpty(images)) {
				p.setHeadImage(images.get(0));
				p.setImages(StringUtils.join(images, ","));
			} else {
				p.setHeadImage("");
				p.setImages("");
			}
			p.setCodes(StringUtils.join(codes, ","));
		} else {
			p.setHeadImage("");
			p.setImages("");
			p.setCodes("");
		}
		productService.updateAllFields(p);
	}

}
